package com.tchhy.mvplibrary.rx

import android.app.Activity
import android.content.Intent
import com.google.gson.Gson
import com.tchhy.basemodule.basedata.TokenHelper
import com.tchhy.basemodule.utils.MedicineUsageNoticeClearUtil
import com.tchhy.mvplibrary.presenter.view.BaseView
import com.tchhy.provider.data.common.BaseResp
import com.tchhy.provider.data.common.EmptyResp
import com.tchhy.provider.rx.RxErrorHandle
import com.tchhy.toast.ToastUtils
import com.trello.rxlifecycle2.LifecycleProvider
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import retrofit2.HttpException


/**
 * Describe: RxJava线程戏相关
 *
 */
open class WechatLoginObserver<T>(
    var context: Activity,
    val lifecycleProvider: LifecycleProvider<*>,
    val view: BaseView?,
    private val onSuccess: (T) -> Unit
) : Observer<BaseResp<T>> {

    open fun onErrorMessage(errorMessage: String) {
       ToastUtils.show(errorMessage)
    }

    open fun unWechatUnBind(){}


    override fun onNext(t: BaseResp<T>) {
        if (t.status == 0) {
            if (t.data != null) {
                onSuccess.invoke(t.data!!)
            } else {
                onDataNull()
            }
        } else if(t.status == 603) {
            unWechatUnBind()
        }else {
            onErrorMessage(t.message)
        }

    }

    open fun onDataNull() {

    }

    override fun onComplete() {
        view?.dismissLoading()
    }

    override fun onSubscribe(d: Disposable) {
        view?.showLoading()
    }

    override fun onError(e: Throwable) {
        view?.dismissLoading()
        if (e is HttpException) {
            val errorBody = e.response()?.errorBody()?.string()
            val emptyResponse = Gson().fromJson(errorBody, EmptyResp::class.java)
            when (emptyResponse.status) {
                ServiceCodeEnum.CODE_ACCESS_TOKEN_EXPIRED,
                ServiceCodeEnum.CODE_ACCESS_TOKEN_VALIDATE_ERROR,
                ServiceCodeEnum.CODE_ACCESS_REFRESH_TOKEN_VALIDATE_ERROR -> {
                    jumpToLoginActivity()
                }
            }
            view?.onError(emptyResponse.message)
        }
        view?.onError(RxErrorHandle(e).error())
    }

    private fun jumpToLoginActivity() {
        val clz = Class.forName("com.tchhy.tcjk.ui.login.activity.LoginNewActivity")
        val intent = Intent(context, clz)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        TokenHelper.clearAuthorization(context)
        MedicineUsageNoticeClearUtil.cancelAllTask()
        context.startActivity(intent)
    }
}